import { create } from 'zustand';
import { invoke } from '@tauri-apps/api/core';

// --- Type Definitions ---

export interface FileEntry {
  name: string;
  is_dir: boolean;
  size: number;
  modified: number;
}

export type OpenAIProvider = {
  type: 'OpenAI';
  id: string;
  name: string;
  api_key: string;
  model: string;
};

export type ProviderConfig = OpenAIProvider; // Add other provider types with | in the future

export interface AppConfig {
  active_provider_id: string | null;
  providers: ProviderConfig[];
}

// --- Zustand Store ---

interface AppState {
  // File Explorer State
  currentPath: string;
  files: FileEntry[];
  isLoading: boolean;

  // Config State
  appConfig: AppConfig | null;
}

interface AppActions {
  // File Explorer Actions
  setPath: (path: string) => void;
  setFiles: (files: FileEntry[]) => void;
  setLoading: (loading: boolean) => void;

  // Config Actions
  loadConfig: () => Promise<void>;
  saveConfig: (config: AppConfig) => Promise<void>;
  setAppConfig: (config: AppConfig) => void;
  addProvider: (provider: ProviderConfig) => Promise<void>;
  updateProvider: (provider: ProviderConfig) => Promise<void>;
  deleteProvider: (providerId: string) => Promise<void>;
  setActiveProviderId: (providerId: string | null) => Promise<void>;
}

export const useAppStore = create<AppState & AppActions>((set, get) => ({
  // --- Initial State ---
  currentPath: '/',
  files: [],
  isLoading: false,
  appConfig: null,

  // --- Actions ---
  setPath: (path) => set({ currentPath: path }),
  setFiles: (files) => set({ files, isLoading: false }),
  setLoading: (loading) => set({ isLoading: loading }),

  loadConfig: async () => {
    try {
      const config = await invoke<AppConfig>('get_config');
      set({ appConfig: config });
    } catch (error) {
      console.error("Failed to load config:", error);
    }
  },

  saveConfig: async (config: AppConfig) => {
    try {
      await invoke('save_config', { config });
      set({ appConfig: config });
    } catch (error) {
      console.error("Failed to save config:", error);
    }
  },

  setAppConfig: (config: AppConfig) => set({ appConfig: config }),

  addProvider: async (provider) => {
    const { appConfig, saveConfig } = get();
    if (!appConfig) return;
    const newConfig = { ...appConfig, providers: [...appConfig.providers, provider] };
    await saveConfig(newConfig);
  },

  updateProvider: async (provider) => {
    const { appConfig, saveConfig } = get();
    if (!appConfig) return;
    const newProviders = appConfig.providers.map(p => p.id === provider.id ? provider : p);
    const newConfig = { ...appConfig, providers: newProviders };
    await saveConfig(newConfig);
  },

  deleteProvider: async (providerId) => {
    const { appConfig, saveConfig } = get();
    if (!appConfig) return;
    const newProviders = appConfig.providers.filter(p => p.id !== providerId);
    const newConfig = { ...appConfig, providers: newProviders };
    await saveConfig(newConfig);
  },

  setActiveProviderId: async (providerId) => {
    const { appConfig, saveConfig } = get();
    if (!appConfig) return;
    const newConfig = { ...appConfig, active_provider_id: providerId };
    await saveConfig(newConfig);
  },
}));